/* Copyright (C) 2009, 2011 Christofer Jonsson
 *
 * This file is part of FXH.
 *
 * FXH is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FXH is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FXH.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "fxh_util.h"
#include "fxh_error.h"
#include <stdio.h>
#include <errno.h>
#include <unistd.h>

fxh_status_t fxh_util_file_size(const char *path, uint64_t *size)
{
   FILE *file = fopen(path, "rb");
   off_t tmp_size = 0;

   if (file == NULL)
   {
      FXH_ERROR("Unable to open file %s: %s", path, strerror(errno));
      return FXH_FAILURE;
   }

   if (fseeko(file, 0, SEEK_END) != 0)
   {
      FXH_ERROR("Seek failed in %s: %s", path, strerror(errno));
      (void)fclose(file);
      return FXH_FAILURE;
   }

   tmp_size = ftello(file);

   if (tmp_size < 0)
   {
      FXH_ERROR("Tell failed in %s: %s", path, strerror(errno));
      (void)fclose(file);
      return FXH_FAILURE;
   }
   
   if (fclose(file) != 0)
   {
      FXH_ERROR("Unable to close file %s: %s", path, strerror(errno));
      return FXH_FAILURE;
   }

   *size = (uint64_t)tmp_size;
   return FXH_SUCCESS;
}

fxh_status_t fxh_util_basename(const char *path, size_t length, size_t *pos)
{
   size_t index = 0;

   if (path == NULL || length == 0)
      return FXH_FAILURE;

   index = length - 1;

   if (path[index] == '/')
      return FXH_FAILURE;

   while (index > 0)
   {
      if (path[index] == '/')
      {
	 *pos = index + 1;
	 return FXH_SUCCESS;
      }

      --index;
   }

   *pos = index;
   return FXH_SUCCESS;
}

void* fxh_util_malloc(size_t size)
{
   void *mem = malloc(size);

   if (mem == NULL)
   {
      FXH_ERROR("Malloc failed");
      exit(EXIT_FAILURE);
   }
   
   return mem;
}

void fxh_util_free(void *mem)
{
   free(mem);
}
